package com.ScoresSystem.controller;


import com.ScoresSystem.utils.Result;
import com.ScoresSystem.pojo.Teacher;
import com.ScoresSystem.service.TeacherService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;

@RestController
@RequestMapping("/teacher")
public class TeacherController {

    @Autowired
    TeacherService teacherService;

    // 登陆
    @RequestMapping("/login")
    public Result<Teacher> login(String userName, String password, String userCode, HttpSession session) {
        // 获取session中的验证码
        String systemCode = (String) session.getAttribute("systemCode");
        if(systemCode.equalsIgnoreCase(userCode)){
            // 验证码正确, 验证用户名和密码
            Teacher teacher = teacherService.login(userName, password);
            if (teacher != null) {
                session.setAttribute("nowusername",teacher.getTname());
                return new Result<>("0", "登录成功");
            } else {
                return new Result<>("1", "用户名或密码错误");
            }
        }
        return new Result<>("2", "验证码错误");
    }

    // 修改密码
    @RequestMapping("/updatePassword")
    public Result<String> updatePassword(String oldPassword, String newPassword, HttpSession session) {
        String nowUserName = String.valueOf(session.getAttribute("nowusername"));
        //检查老密码是否正确
        Teacher teacher = teacherService.findTeacher(nowUserName,oldPassword);
        if (teacher == null){
            return new Result<>("1", "旧密码错误");
        }
        int result = teacherService.updatePassword(nowUserName,newPassword);
        if (result > 0) {
            return new Result<>("0", "修改成功");
        }
        return new Result<>("1", "修改失败");
    }

}
